﻿using Aspose.Cells;
using System;
using System.Collections.Generic;

namespace QuickFill.Services
{
    public class ExcelService
    {
        public List<Dictionary<string, object>> ReadExcelData(string filePath)
        {
            try
            {
                // 加载Excel工作簿
                Workbook workbook = new Workbook(filePath);
                Worksheet worksheet = workbook.Worksheets[0];

                // 获取行数和列数
                int rowCount = worksheet.Cells.MaxDataRow + 1;
                int colCount = worksheet.Cells.MaxDataColumn + 1;

                if (rowCount < 2 || colCount < 1)
                    throw new Exception("Excel数据格式不正确：至少需要一行标题和一行数据");

                // 读取标题行
                var headers = new string[colCount];
                for (int col = 0; col < colCount; col++)
                {
                    var cell = worksheet.Cells[0, col];
                    headers[col] = cell.StringValue?.Trim();

                    if (string.IsNullOrEmpty(headers[col]))
                        throw new Exception($"第{col + 1}列标题为空");
                }

                // 检查第一列是否是文件夹名称
                if (headers[0] != "FolderName")
                    throw new Exception("Excel第一列必须是'FolderName'");

                // 读取数据行
                var data = new List<Dictionary<string, object>>();

                for (int row = 1; row < rowCount; row++)
                {
                    var record = new Dictionary<string, object>();

                    for (int col = 0; col < colCount; col++)
                    {
                        string key = headers[col];
                        var cell = worksheet.Cells[row, col];

                        // 处理不同类型的值
                        switch (cell.Type)
                        {
                            case CellValueType.IsBool:
                                record[key] = cell.BoolValue;
                                break;
                            case CellValueType.IsDateTime:
                                record[key] = cell.DateTimeValue;
                                break;
                            case CellValueType.IsNumeric:
                                record[key] = cell.DoubleValue;
                                break;
                            default:
                                record[key] = cell.StringValue?.Trim();
                                break;
                        }
                    }

                    data.Add(record);
                }

                if (data.Count == 0)
                    throw new Exception("Excel中没有有效数据");

                return data;
            }
            catch (Exception ex)
            {
                throw new Exception($"读取Excel失败: {ex.Message}");
            }
        }
    }
}